
<html>
<head>
<style type="text/css">

table{	
border-collapse:collapse;	
}
tr.tables
{
border:1px solid darkgrey;
background-color:black;
color:white;
}

tr.attributes
{
border:1px solid white;
background-color:#303030;
color:white;
}
tr.rowa
{
border:1px solid white;
background-color:#D0D0D0;
color:black;
}
tr.rowb
{
border:1px solid white;
background-color:white;
color:black;
}
</style>



</head>
<body onload=updateTextboxes('actors')>

<?php

print "<div align=center><form action=search.php method=post>";
print "<input type=text maxlength=100 name=query size='150' value=\"". htmlspecialchars($raw_query)."\"></input>";
print "<input type=submit  value=Run></input></form><br>";

//SOuRCE FOR LINKS HERE
print "<div align=center><table width=800>
		<tr class=rowb>
		<td><a href=addmovie.php><b>Add Movie</b></a></td>
		<td><a href=addmovieactor.php><b>Add Movie Actor</b></a></td>
		<td><a href=addmoviedirector.php><b>Add Movie Director</b></a></td>
		<td><a href=add_actor_director.php><b>Add Actor or Director</b></a>	</td>
		</tr>
		</table></div>";

print "<script type=text/javascript>

var roles = {};

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, '&#39');
}

function updateTextboxes(listname){
	var list = document.getElementById(listname);
	var i;
	document.getElementById('rolelist').innerHTML = '';
	for( i =0; i < list.options.length; i++){
		if(list.options[i].selected){
			var textid='r_' + list.options[i].value;
			
			var textbox_input = '<input type=text onkeyup=editTextbox(\''+
								textid +'\') maxlength=50 id=' 
								+textid +' name='+ textid + ' ';
								
			if(roles[textid] != null){
				textbox_input += 'value = \'' + htmlEntities(roles[textid]) +'\' ';
			}					 
			else 
				textbox_input += 'value = \"\" ';
				
			textbox_input +='></input>';
			
			document.getElementById('rolelist').innerHTML += '<tr><td><b>'+list.options[i].text + '</b></td>' + 
															'<td>'+textbox_input + '</td></tr> ';
		}
	}
}
function editTextbox(idname){
		roles[idname] = document.getElementById(idname).value;
}

redirectTime =2500;
redirectURL = '';
function timedRedirect(url) {
	redirectURL = url;
	setTimeout('location.href = redirectURL;',redirectTime);
}

</script>"; 
									
function connect_to_server(){
	$DB="CS143";
	$db_connection = mysql_connect("localhost", "cs143", "");
	if(!$db_connection) {
		$errmsg = mysql_error($db_connection);
		print "Connection failed: " .$errmsg ."<br />";
		exit(1);
	}
	mysql_select_db("$DB", $db_connection);
	return $db_connection;

}

function make_query($command, $db_connection){
		
	$resTable = mysql_query($command, $db_connection);
	if(!$resTable) {
		$errmsg = mysql_error($db_connection);

		if($command != ""){
			print "Query fetch failed: " .$errmsg ."<br />";
		}

		exit(1);
	
	}
	return $resTable;
	
}

$data["actors"] = $_POST["actors"];
$data["movies"] = $_POST["movies"];

$conn=connect_to_server();
$getActorsQuery = "SELECT first,last,id FROM Actor;";
$getMoviesQuery = "SELECT DISTINCT title,id FROM Movie;";


if($_SERVER['REQUEST_METHOD'] ==  'POST' ){
		$mid = $_POST["mid"];
		$aid = $_POST["aid"];
}
else if($_SERVER['REQUEST_METHOD'] ==  'GET' ){
		$mid=$_GET["mid"];
		$aid=$_GET["aid"];
}

if($aid != null){
		print "<br><div align=left>
		<input value='Back To Actor' type=button onclick='window.location=\"actor?id=$aid\"'></input><br></div>";
}
else if($mid != null){
		print "<br><div align=left>
				<input value='Back To Movie' type=button onclick='window.location=\"movie?id=$mid\"'></input><br></div>";
}

if($aid == null){
	$res=make_query($getActorsQuery, $conn);
	$i=0;

	while($row =  mysql_fetch_row($res)){
		$form["actors"][$i]["name"] = $row[0] . " " .$row[1];
		$form["actors"][$i]["id"] = $row[2];
		$form["actors"][$i]["selected"]=false;
		if($data["actors"]!=null){
			for($j=0; $j < sizeof($data["actors"]); $j++){
				if($row[2] == $data["actors"][$j]){
					$data["actors_details"][$j]["name"] = $form["actors"][$i]["name"];
					$data["actors_details"][$j]["id"]=$form["actors"][$i]["id"];
				}
			}
		}
		
		$i++;
	}
}
else{
		if(preg_match("/^[0-9]+$/", $aid)){
				$query = "SELECT first,last FROM Actor WHERE id=". $aid.";";
				$res = make_query($query, $conn);
				$row=mysql_fetch_row($res);
				if($row == null){
						print "<h1>Actor Not Found</h1>
						   <img src='data/filenotfound.png'/><br>
						   <b>The Actor with the id $aid does not exist! please select another movie.</b>";
				
	
						exit();
				}
				else
					print "<h1>Add Movie Roles</h1><h2>Actor: ".$row[0]." ".$row[1]."</h2>";
				
		}
		else{
			print "<h1>Invalid Actor Id</h1>
			   <img src='data/error.png'/><br>
			   <b>The id \"$aid\" is not an acceptable id.</b>
			   ";
			exit();
		}

}

if($mid == null){
	$res=make_query($getMoviesQuery, $conn);
	$i=0;
	
	$error=false;
	while($row =  mysql_fetch_row($res)){
		$form["movies"][$i]["title"] = $row[0];
		$form["movies"][$i]["id"] = $row[1];
		$form["movies"][$i]["selected"]=false;
		if($data["movies"]!=null){
			for($j=0; $j < sizeof($data["movies"]); $j++){
				if($row[1] == $data["movies"][$j]){
					$data["movies_details"][$j]["title"] = $form["movies"][$i]["title"];
					$data["movies_details"][$j]["id"]=$form["movies"][$i]["id"] = $row[1];
				}
			}
		}
		$i++;
	}
	
}
else{
		if(preg_match("/^[0-9]+$/", $mid)){
				$query = "SELECT title, year FROM Movie WHERE id=". $mid."";
				$res = make_query($query, $conn);
				$row=mysql_fetch_row($res);
				if($row == null){
						print "<h1>Movie Not Found</h1>
						   <img src='data/filenotfound.png'/><br>
						   <b>The Movie with the id $mid does not exist! please select another movie.</b>";
						exit();
				}
				else
					print "<h1>Add Actor Roles</h1><h2>Movie: ".$row[0]."(".$row[1].")</h2>";
				
		}
		else{
			print "<h1>Invalid Movie Id</h1>
			   <img src='data/error.png'/><br>
			   <b>The id \"$mid\" is not an acceptable id.</b>
			   ";
			exit();
		}
}

		print"<form action=addmovieactor.php method=post>
		<table align=center><tr><td><b>";
		if($aid == null && $mid != null){
				print "Choose Actors";
				print "<input type=hidden readonly=\"readonly\" name=mid value=".$mid . " />";
				
		}
		else if($mid == null && $aid != null){
				print "Choose Movies";
				print "<input type=hidden readonly=\"readonly\" name=aid value=".$aid . " />";
		}
		else if($mid == null && $aid == null){
				print "Choose Movie/Actor Pair";
		}
		print "</b></td>
		</tr>
		<tr>
		<td>";
	
		if($aid == null && $mid != null){
			print "<select onchange=\"updateTextboxes('actors')\" id='actors' name='actors[]' multiple=true size=10>";
			for($i =0; $i < sizeof($form["actors"]); $i++){
					
					if($form["actors"][$i]["selected"]==false)
						print "<option value=\"".$form["actors"][$i]["id"]."\">".$form["actors"][$i]["name"]."</option>";
					else
						print "<option selected=true value=\"".$form["actors"][$i]["id"]."\">".$form["actors"][$i]["name"]."</option>";
					
			}
			print "</select>";
		}
		else if($mid == null && $aid != null){
			print "<select onchange=\"updateTextboxes('movies')\" id='movies'   name='movies[]' multiple=true size=10>";
			for($i =0; $i < sizeof($form["movies"]); $i++){
					if($form["movies"][$i]["selected"]==false)
						print "<option value=\"".$form["movies"][$i]["id"]."\">".$form["movies"][$i]["title"]."</option>";
					else
						print "<option selected=true value=\"".$form["movies"][$i]["id"]."\">".$form["movies"][$i]["title"]."</option>";
			}
			print "</select>";
		}
		else if($mid == null && $aid == null){
			print "<select name='movies[]' size=10>";
			for($i =0; $i < sizeof($form["movies"]); $i++){
					if($i!=0)
						print "<option value=\"".$form["movies"][$i]["id"]."\">".$form["movies"][$i]["title"]."</option>";
					else
						print "<option selected=true value=\"".$form["movies"][$i]["id"]."\">".$form["movies"][$i]["title"]."</option>";
			}
			print "</select></td><td>";
			print "<select   onchange=\"updateTextboxes('actors')\" id='actors'   name='actors[]' size=10>";
			for($i =0; $i < sizeof($form["actors"]); $i++){
					
					if($i!=0)
						print "<option value=\"".$form["actors"][$i]["id"]."\">".$form["actors"][$i]["name"]."</option>";
					else
						print "<option selected=true value=\"".$form["actors"][$i]["id"]."\">".$form["actors"][$i]["name"]."</option>";
					
			}
			print "</select>";
		}
		
		print "
		</select>
		</td>
		<td><table  align=center id=rolelist>
		";
		
		print "</table>
		</td>
		</tr>
		</table>
		<br>
		<br>
		<br>
		<input type=submit  name=AddRole value='Add Role'></input>";
		print "<br></form>";
		

		if(isset($_POST["AddRole"])){
			if($error ==false){
				
				if($aid == null && $mid != null){
					for($i=0; $i < sizeof($data["actors"]); $i++){
						$role_unesc=$_POST["r_".$data["actors_details"][$i]["id"]];
						$role = mysql_real_escape_string($role_unesc, $conn);
						
						if($role != NULL){
							
							$insertquery = "INSERT INTO MovieActor (mid, aid, role) VALUES(".
							$mid."," . $data["actors_details"][$i]["id"] .",\"".$role
							."\")";
							$updatequery = "UPDATE MovieActor SET role=".
							"\"".$role.
							"\" WHERE mid=" . $mid.
							" AND aid=" . $data["actors_details"][$i]["id"] . ";";
							
							$existsquery="SELECT * FROM MovieActor WHERE mid=".
							$mid.
							" AND aid=" . $data["actors_details"][$i]["id"].";" ;
							
							$row=mysql_fetch_row(make_query($existsquery, $conn));
							if($row != null){
								make_query($updatequery, $conn);
								print "<font color=orange>Updated <b>".$data["actors_details"][$i]["name"]
									."</b> As <b>$role_unesc</b></font><br>";
							}
							else{
								make_query($insertquery, $conn);
								print "<font color=green>Added <b>".$data["actors_details"][$i]["name"]
									."</b> As <b>$role_unesc</b></font><br>";
							}
							
						}
						else
							print "<font color=red><b>".$data["actors_details"][$i]["name"]
									."</b> was not added (Empty Role)<br></font><br>";
						
					}
					
					//print "<script type=text/javascript>
					//		window.location = \"movie?id=$mid\"
					//		</script>";
				}
				if($mid == null && $aid != null){
					for($i=0; $i < sizeof($data["movies"]); $i++){
						$role_unesc=$_POST["r_".$data["movies_details"][$i]["id"]];
						$role = mysql_real_escape_string($role_unesc, $conn);
						
						if($role != NULL){
							$insertquery = "INSERT INTO MovieActor (mid, aid, role) VALUES(".
							$data["movies_details"][$i]["id"]."," . $aid .",\"".$role
							."\")";
							$updatequery = "UPDATE MovieActor SET role=".
							"\"".$role.
							"\" WHERE mid=" . $data["movies_details"][$i]["id"].
							" AND aid=" . $aid . ";";
							
							$existsquery="SELECT * FROM MovieActor WHERE mid=".
							$data["movies_details"][$i]["id"].
							" AND aid=" . $aid .";" ;
							
							$row=mysql_fetch_row(make_query($existsquery, $conn));
							if($row != null){
								make_query($updatequery, $conn);
								print "<font color=orange>Updated <b>"
									.$data["movies_details"][$i]["title"]."</b> With Role <b>$role_unesc</b></font><br>";
							}
							else{
								make_query($insertquery, $conn);
								print "<font color=green>Added "
									.$data["movies_details"][$i]["title"]."</b> With Role <b>$role_unesc</b></font><br>";
							}
						}
						else
							print "<font color=red><b>". $data["movies_details"][$i]["title"]
							."</b> was not added (Empty Role)<br></font><br>";
						
						
					}
					//print "<script type=text/javascript>
					//		window.location = \"actor?id=$aid\";
					//		</script>";
				}
				if($mid == null && $aid == null){
					for($i=0; $i < sizeof($data["movies"]); $i++){
						$role_unesc=$_POST["r_".$data["actors_details"][$i]["id"]];
						$role = mysql_real_escape_string($role_unesc, $conn);
						
						if($role != NULL){
							$insertquery = "INSERT INTO MovieActor (mid, aid, role) VALUES(".
							$data["movies_details"][$i]["id"]."," . $data["actors_details"][$i]["id"] .
							",\"".$role
							."\")";
							$updatequery = "UPDATE MovieActor SET role=".
							"\"".$role.
							"\" WHERE mid=" . $data["movies_details"][$i]["id"].
							" AND aid=" . $data["actors_details"][$i]["id"] . ";";
							
							$existsquery="SELECT * FROM MovieActor WHERE mid=".
							$data["movies_details"][$i]["id"].
							" AND aid=" . $data["actors_details"][$i]["id"].";" ;
							
							$row=mysql_fetch_row(make_query($existsquery, $conn));
							if($row != null){
								make_query($updatequery, $conn);
								print "<font color=orange>Updated <b>".$data["actors_details"][$i]["name"]
									."</b> in  <b>".$data["movies_details"][$i]["title"]."</b> As <b>$role_unesc</b></font><br>";
							}
							else{
								make_query($insertquery, $conn);
								print "<font color=green>Added <b>".$data["actors_details"][$i]["name"]
									."</b> in  <b>".$data["movies_details"][$i]["title"]."</b> As <b>$role_unesc</b></font><br>";
							}
							
						}
						else
							print "<font color=red><b>".$data["actors_details"][$i]["name"]
									."</b> in  <b>".$data["movies_details"][$i]["title"]."</b> was not added (Empty Role)<br></font><br>";
						
					}
				}
				
				
				
			}
			else{
				print "There was an error in the form. Please fix the error.<br>";
				
			}
			print "</div>";
		}
		






?>

<br>
</body>
</html>

